package com.vichat.res.service.impl;

import com.vichat.common.enums.RecordType;
import com.vichat.common.util.NumberUtils;
import com.vichat.core.dao.BaseDaoI;
import com.vichat.res.entity.FtpConfig;
import com.vichat.res.entity.SysHost;
import com.vichat.res.entity.SysRecord;
import com.vichat.res.service.ICfgService;
import com.vichat.user.entity.SysBusiRecord;
import com.vichat.user.entity.UserBasic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service("cfgService")
public class CfgServiceImpl implements ICfgService {
    private static transient final Logger logger = LoggerFactory.getLogger(CfgServiceImpl.class);

    @Autowired
    private BaseDaoI<FtpConfig> ftpCfgDao;

    @Autowired
    private BaseDaoI<SysHost> sysHostDao;

    @Autowired
    private BaseDaoI<SysRecord> daoSysRecord;


    public List<FtpConfig> queryFtpConfig()throws Exception{
        StringBuilder hql = new StringBuilder();
        hql.append("from FtpConfig where state = 1");
        HashMap params = new HashMap();
        return ftpCfgDao.find(hql.toString(),params);
    }

    public void executeSql(String sql) throws Exception{
        sysHostDao.executeSql(sql);
    }

    /**
     * 保存录音配置
     * @param sysRecord
     * @throws Exception
     */
    public void saveSysRecord(SysRecord sysRecord,long[] srvIds) throws Exception{
        List<SysRecord> sysRecords = this.querySysRecord(sysRecord);
        if(!sysRecords.isEmpty()){
            this.updSysRecord(sysRecord);
        } else {
            if(srvIds.length == 0){
                logger.error("未找到录制服务配置列表，请配置静态表。");
            }
            Random random = new Random();
            int index = random.nextInt(srvIds.length);
            sysRecord.setSrvId(srvIds[index]);
            daoSysRecord.save(sysRecord);
        }
    }

    /**
     * 查询录制开关列表
     * @param sysRecord
     * @return
     * @throws Exception
     */
    private List<SysRecord> querySysRecord(SysRecord sysRecord) throws Exception{
        HashMap params = new HashMap();
        String hql = "from SysRecord where 1 = 1";
        if(NumberUtils.isNotNullOrZero(sysRecord.getRid())){
            hql += " and rid= :rid";
            params.put("rid", sysRecord.getRid());
        }
        return daoSysRecord.find(hql,params);
    }

    /**
     * 修改录制开关状态
     * @param sysRecord
     * @throws Exception
     */
    private void updSysRecord(SysRecord sysRecord)throws Exception{
        String sql = "update cfgdb.sys_record set rec_state='" + sysRecord.getRecState() + "'";
        sql += " where rid=" + sysRecord.getRid();
        daoSysRecord.executeSql(sql);
    }
}
